#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMenu>
#include <QMenuBar>
#include <QAction>
#include <QFileDialog>
#include <QStatusBar>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QMenuBar* menubar = this->menuBar();
    QMenu* menu1 = new QMenu("文件 (&f)");
    menubar->addMenu(menu1);

    QAction* action1 = new QAction("读取 (&o)");
    QAction* action2 = new QAction("保存 (&s)");
    menu1->addAction(action1);
    menu1->addAction(action2);

    plain = new QPlainTextEdit;
    this->setCentralWidget(plain);

    connect(action1,&QAction::triggered,this,&MainWindow::readfile);
    connect(action2,&QAction::triggered,this,&MainWindow::savefile);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::readfile()
{
    //显示文件对话框
    QString filename = QFileDialog::getOpenFileName(this);
    QStatusBar*statusbar = this->statusBar();
    statusbar->showMessage(filename);

    //创建文件并且打开
    QFile file(filename);
    bool ret = file.open(QIODevice::ReadOnly); //只读
    if(!ret)
    {
        statusbar->showMessage("打开失败: " + filename);
        return;
    }

    //读取文件
    QString str = file.readAll();

    //关闭文件
    file.close();

    //设置文本
    plain->setPlainText(str);
}

void MainWindow::savefile()
{
    //获取要保存的文件名
    QString filename = QFileDialog::getSaveFileName();
    QStatusBar* statusbar = this->statusBar();
    statusbar->showMessage(filename);

    QFile file(filename);
    bool ret = file.open(QIODevice::WriteOnly); //只写
    if(!ret)
    {
        statusbar->showMessage("打开失败: " + filename);
        return;
    }

    //写入的内容
    QString str = plain->toPlainText();
    file.write(str.toUtf8());

    //关闭文件
    file.close();
}

